package com.share.finance.risk.rules.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.finance.risk.rules.mapper.ProjectStrategyMapper;
import com.share.finance.risk.rules.mapper.StrategyConfMapper;
import com.share.finance.risk.rules.model.db.ProjectStrategy;
import com.share.finance.risk.rules.model.db.StrategyConf;
import com.share.finance.risk.rules.model.vo.ProjectIdAndVersion;
import com.share.finance.risk.rules.service.IProjectStrategyService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 策略集  服务实现类
 * </p>
 *
 * @author author
 * @since 2023-12-25
 */
@Service
public class ProjectStrategyServiceImpl extends ServiceImpl<ProjectStrategyMapper, ProjectStrategy> implements IProjectStrategyService {
    @Resource
    private ProjectStrategyMapper projectStrategyMapper;

    @Resource
    private StrategyConfMapper strategyConfMapper;

    @Override
    public Map<String, List<StrategyConf>> mapByProjectIdAndVersion(List<ProjectIdAndVersion> paramList) {
        Map<String, List<StrategyConf>> reMap = new HashMap<>();
        if (CollectionUtils.isEmpty(paramList)) {
            return reMap;
        }

        List<ProjectStrategy> list = projectStrategyMapper.listByProjectIdAndVersion(paramList);
        if (!CollectionUtils.isEmpty(list)) {
            //先查
            Map<String, StrategyConf> tmpMap = new HashMap<>();
            Set<String> strategyId = list.stream().map(e -> e.getStrategyId()).collect(Collectors.toSet());
            List<StrategyConf> strategyConfList = strategyConfMapper.selectBatchIds(strategyId);
            if (!CollectionUtils.isEmpty(strategyConfList)) {
                strategyConfList.stream().forEach(e -> tmpMap.put("" + e.getId(), e));
            }

            //遍历
            for (ProjectStrategy item : list) {
                String key = item.getProjectId() + "-" + item.getProjectVersion();
                List<StrategyConf> strategyConfs = reMap.get(key);
                if (CollectionUtils.isEmpty(strategyConfs)) {
                    strategyConfs = new LinkedList<>();
                    reMap.put(key, strategyConfs);
                }

                StrategyConf strategyConf = tmpMap.get(item.getStrategyId());
                if (strategyConf != null) {
                    strategyConfs.add(strategyConf);
                }
            }
        }
        return reMap;
    }
}
